// 安装包
// npm install socket.io-client @socket.io/client-dist
import { io } from 'socket.io-client';
// import { io as ioClient } from '@socket.io/client-dist';

const SOCKET_ENDPOINT = 'http://192.168.10.140:4999'; // 根据您的服务器设置更改此URL

let socket;

function connect(config) {

  console.log('socket正常加载连接')
  const endpoint = SOCKET_ENDPOINT
  const queryParams = config.queryParams || {};

  // 将查询参数附加到URL
  const queryString = new URLSearchParams(queryParams).toString();
  const urlWithQueryParams = `${endpoint}?${queryString}`;

  console.log(endpoint)
  console.log(urlWithQueryParams)
  // 使用相同的Socket.IO实例
  socket = io(urlWithQueryParams, {
    reconnection: true, // 启用自动重连
    // reconnectionAttempts: Infinity, // 无限次重连尝试
    reconnectionAttempts:10,
    reconnectionDelay: 2000, // 重连间隔（毫秒）
    reconnectionDelayMax: 5000, // 最大重连间隔（毫秒）
  });

  socket.on('connect', () => {
    // 获取scoket的id
    console.log('Client connection ID:', socket.id); // 获取并打印连接ID
    sessionStorage.setItem("online_id", socket.id)
  });
  // 或者使用兼容Vite的ES模块版本
  // socket = ioClient(SOCKET_ENDPOINT);

  return socket
}


export { socket,connect};